﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraScheduler;
using COMOSOFT.Class;

namespace COMOSOFT.JobManagement.USC
{
    public partial class UscSchedule : UserControl
    {        
        public UscSchedule()
        {
            InitializeComponent();
        }
        ClassShare cls = new ClassShare("UscSchudule");
        Task task;
        public SchedulerControl GetSchedule()
        {
            return scheduler;
        }     

        private void OnAppointmentChangedInsertedDeleted(object sender, PersistentObjectsEventArgs e)
        {
            schuduleManageBindingSource.EndEdit();
            schuduleManageTableAdapter.Update(dataSet_Schudule.SchuduleManage);
            dataSet_Schudule.SchuduleManage.AcceptChanges();
            LoadData();
        }        

        private void UscSchedule_Load(object sender, EventArgs e)
        {
            if (task == null || task.Status == TaskStatus.Running)
            {
                splashScreenManager1.ShowWaitForm();
                schedulerStorage1.Appointments.DataSource = null;                
                task = Task.Factory.StartNew(() => LoadData());
                task.ContinueWith(tt => FillTable());                               
            }
        }
        private delegate void dlgFillTable();
        private void FillTable()
        {
            if (InvokeRequired)
            {
                this.Invoke(new dlgFillTable(FillTable));
            }
            else
            {
                schedulerStorage1.Appointments.DataSource = dataSet_Schudule.SchuduleManage;
                scheduler.ActiveViewType = SchedulerViewType.WorkWeek;
                splashScreenManager1.CloseWaitForm();
            }
        }
        private void LoadData()
        {            
            schuduleManageTableAdapter.Fill(dataSet_Schudule.SchuduleManage,ClassShare.Usid);
        }

        private void schedulerStorage1_AppointmentsInserted(object sender, PersistentObjectsEventArgs e)
        {
            try
            {
                schuduleManageBindingSource.EndEdit();
                schuduleManageTableAdapter.Update(dataSet_Schudule.SchuduleManage);
                dataSet_Schudule.SchuduleManage.AcceptChanges();
                int index = dataSet_Schudule.SchuduleManage.Rows.Count - 1;
                int id = Convert.ToInt32(dataSet_Schudule.SchuduleManage.Rows[index]["APID"]);
                cls.UpdateData("sp_SchuduleUpdateEID", new string[] { "@APID", "@EID" }, new object[] { id, ClassShare.Usid });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }       
    }
}
